import axios from 'axios'
// import Qs from 'qs'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import store from '@/store'
import router from '@/router/index'

let loadingRequestCount = 0
let loadingInstance = null
const showLoading = () => {
  if (loadingRequestCount === 0) {
    // loadingInstance = Loading.service({ background: 'rgba(0, 0, 0, 0.4)', target: '.el-table' })
    loadingInstance = ElLoading.service({ background: 'rgba(0, 0, 0, 0.4)' })
  }
  loadingRequestCount++
}
const hideLoading = () => {
  if (loadingRequestCount <= 0) return
  loadingRequestCount--
  if (loadingRequestCount === 0) {
    setTimeout(() => {
      loadingInstance.close()
    }, 50)
  }
}

const service = axios.create({
  baseURL: import.meta.env.MODE==='development'?'/api':'http://101.33.200.135:8080', // url = base url + request url
  // transformRequest: [data => {
  //   // 对 data 进行任意转换处理
  //   // return Qs.stringify(data)
  // }]
  timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    // 给headers加上token
    
    if (store.getters.token) {
      config.headers['token'] = store.getters.token
    }

    // 请求拦截进来调用显示loading效果
    if (config.loading) {
      showLoading()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response
service.interceptors.response.use(
  response => {
    // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启
    setTimeout(() => {
      hideLoading()
    }, 200)

    const res = response.data
    if (res.success) {
      return res.data
    } else {
      ElMessage({
        message: res.msg || 'Error',
        type: res.msgLevel || 'error',
        duration: 5 * 1000
      })

      return Promise.reject(res.msg || 'Error')
    }
  },
  error => {
    setTimeout(() => {
      hideLoading()
    }, 200)
    if (error.response) {
      if (error.response.status === 401) {
        if (store.getters.token) {
          store.commit('user/SET_TOKEN', '')
          ElMessageBox.confirm('登录已过期，请重新登录！', '提示', {
            confirmButtonText: '确定',
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showCancelButton: false,
            type: 'error',
            showClose: false
          }).then(() => {
            if (import.meta.env.MODE === 'production') {
              window.location.href = `${window.location.origin}/login`
            } else {
              window.location.href = `${import.meta.env.VUE_APP_BASE}/login`
            }
          })
        }
        return false
      }
    }
    ElMessageBox({
      dangerouslyUseHTMLString: true,
      message: `<p>${error.message}<p><p>${error.response.data.msg || ''}</p>`,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
